// 测试录制和导入导出功能集成

import { FormatConverter } from '../utils/formatConverter.js'
import { recordingService } from '../services/recordingService.js'

/**
 * 测试格式转换功能
 */
export async function testFormatConverter() {
  console.log('开始测试格式转换功能...')
  
  // 测试Playwright脚本
  const playwrightScript = `import { test, expect } from '@playwright/test';

test('登录测试', async ({ page }) => {
  // 打开登录页面
  await page.goto('https://example.com/login');
  
  // 输入用户名
  await page.fill('#username', 'testuser');
  
  // 输入密码
  await page.fill('#password', 'password123');
  
  // 点击登录按钮
  await page.click('.login-button');
  
  // 验证登录成功
  await expect(page.locator('.welcome-message')).toBeVisible();
});`

  try {
    // 测试格式检测
    console.log('1. 测试格式检测...')
    const detectedFormat = FormatConverter.detectFormat(playwrightScript)
    console.log('检测到的格式:', detectedFormat)
    
    if (detectedFormat !== 'playwright') {
      throw new Error('Playwright格式检测失败')
    }
    
    // 测试Playwright转JSONL
    console.log('2. 测试Playwright转JSONL...')
    const jsonlScript = FormatConverter.playwrightToJsonl(playwrightScript)
    console.log('转换后的JSONL长度:', jsonlScript.split('\n').length)
    
    // 测试JSONL转Playwright
    console.log('3. 测试JSONL转Playwright...')
    const convertedPlaywright = FormatConverter.jsonlToPlaywright(jsonlScript, '登录测试')
    console.log('转换后的Playwright脚本长度:', convertedPlaywright.length)
    
    // 测试智能转换
    console.log('4. 测试智能转换...')
    const smartConverted = FormatConverter.smartConvert(playwrightScript, 'jsonl')
    console.log('智能转换结果长度:', smartConverted.split('\n').length)
    
    console.log('格式转换功能测试通过')
    return true
    
  } catch (error) {
    console.error('格式转换功能测试失败:', error)
    return false
  }
}

/**
 * 测试录制服务功能
 */
export async function testRecordingService() {
  console.log('开始测试录制服务功能...')
  
  try {
    // 测试启动录制
    console.log('1. 测试启动录制...')
    const startResult = await recordingService.startRecording({
      startUrl: 'https://example.com/test',
      name: '测试录制会话'
    })
    console.log('启动录制结果:', startResult)
    
    if (!startResult.success) {
      throw new Error('启动录制失败: ' + startResult.error)
    }
    
    // 等待一段时间模拟录制过程
    console.log('2. 模拟录制过程...')
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 测试停止录制
    console.log('3. 测试停止录制...')
    const stopResult = await recordingService.stopRecording()
    console.log('停止录制结果:', stopResult)
    
    if (!stopResult.success) {
      throw new Error('停止录制失败: ' + stopResult.error)
    }
    
    console.log('录制服务功能测试通过')
    return true
    
  } catch (error) {
    console.error('录制服务功能测试失败:', error)
    return false
  } finally {
    // 清理资源
    recordingService.cleanup()
  }
}

/**
 * 测试JSONL解析功能
 */
export function testJsonlParsing() {
  console.log('开始测试JSONL解析功能...')
  
  const jsonlContent = `{"stepNumber": 1, "type": "navigation", "action": "goto", "description": "打开网页", "url": "https://example.com"}
{"stepNumber": 2, "type": "input", "action": "fill", "description": "输入用户名", "selector": "#username", "value": "testuser"}
{"stepNumber": 3, "type": "click", "action": "click", "description": "点击登录", "selector": ".login-button"}`

  try {
    // 测试JSONL格式检测
    console.log('1. 测试JSONL格式检测...')
    const detectedFormat = FormatConverter.detectFormat(jsonlContent)
    console.log('检测到的格式:', detectedFormat)
    
    if (detectedFormat !== 'jsonl') {
      throw new Error('JSONL格式检测失败')
    }
    
    // 测试JSONL解析
    console.log('2. 测试JSONL解析...')
    const steps = FormatConverter.parseJsonl(jsonlContent)
    console.log('解析的步骤数量:', steps.length)
    
    if (steps.length !== 3) {
      throw new Error('JSONL解析步骤数量不正确')
    }
    
    // 测试JSONL生成
    console.log('3. 测试JSONL生成...')
    const generatedJsonl = FormatConverter.generateJsonl(steps)
    console.log('生成的JSONL行数:', generatedJsonl.split('\n').length)
    
    console.log('JSONL解析功能测试通过')
    return true
    
  } catch (error) {
    console.error('JSONL解析功能测试失败:', error)
    return false
  }
}

/**
 * 运行所有测试
 */
export async function runAllTests() {
  console.log('开始运行所有功能测试...\n')
  
  const results = []
  
  // 运行格式转换测试
  results.push(await testFormatConverter())
  console.log('')
  
  // 运行JSONL解析测试
  results.push(testJsonlParsing())
  console.log('')
  
  // 运行录制服务测试
  results.push(await testRecordingService())
  console.log('')
  
  // 统计结果
  const passedTests = results.filter(result => result).length
  const totalTests = results.length
  
  console.log('测试结果统计:')
  console.log(`通过: ${passedTests}/${totalTests}`)
  console.log(`失败: ${totalTests - passedTests}/${totalTests}`)
  
  if (passedTests === totalTests) {
    console.log('所有测试都通过了！录制和导入导出功能集成完成。')
  } else {
    console.log('部分测试失败，请检查相关功能。')
  }
  
  return passedTests === totalTests
}

// 如果直接运行此文件，执行所有测试
if (typeof window !== 'undefined') {
  // 在浏览器环境中，可以在控制台调用 runAllTests()
  window.testRecordingIntegration = runAllTests
}
